package com.jm.common.conf;

import cn.dev33.satoken.exception.NotLoginException;
import com.jm.common.conf.api.Result;
import com.jm.common.conf.api.ResultCode;
import com.jm.common.tool.exception.ErrorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author kong
 */
@Slf4j
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数验证全局处理
     */
    @ExceptionHandler(value = BindException.class)
    public Result<?> methodArgumentNotValidException(BindException e) {
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        log.error("error!", e);
        if (log.isDebugEnabled()) {
            e.fillInStackTrace();
        }
        return Result.fail(error.getDefaultMessage());

    }

    /**
     * 全局手动抛出异常捕捉处理
     */
    @ExceptionHandler(value = ErrorException.class)
    public Result<?> errorHandler(ErrorException e) {
        log.error("error!", e);
        if (log.isDebugEnabled()) {
            e.fillInStackTrace();
        }
        return Result.fail(e.getMessage().replaceAll("com.jianmu.exception.ErrorException: ", ""));
    }


    /**
     * 未登录 或token失效
     */
    @ExceptionHandler(value = NotLoginException.class)
    public Result<?> errorHandler(NotLoginException e) {
        log.error("error!", e);
        if (log.isDebugEnabled()) {
            e.fillInStackTrace();
        }
        return new Result<>().setCode(ResultCode.UNAUTHORIZED.getCode())
                .setInfo(e.getMessage().replaceAll("com.jm.exception.NotLoginException: ", "")).setData(false);
    }

    /**
     * 全局异常捕捉处理
     */
    @ExceptionHandler(value = Exception.class)
    public Result<?> errorHandler(Exception e) {
        log.error("", e);
        if (log.isDebugEnabled()) {
            e.fillInStackTrace();
        }
        if (e.getMessage().contains("io.undertow.server.RequestTooBigException")) {
            return Result.fail("上传失败，请上传0~5M的图片");
        }
        return Result.fail("服务器出差了，请联系管理员!");
    }


    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) throws BindException {
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
        webDataBinder.close();
    }
}
